package com.github.fishlikewater.httppierce.handler;

import com.github.fishlikewater.httppierce.codec.Command;
import com.github.fishlikewater.httppierce.codec.DataMessage;
import com.github.fishlikewater.httppierce.kit.ChannelUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.TooLongFrameException;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * <p>
 * 消息传输处理器
 * </p>
 *
 * @author fishlikewater@126.com
 * @since 2023年02月09日 22:35
 **/
@Slf4j
public class MessageTransferHandler extends SimpleChannelInboundHandler<DataMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DataMessage msg) {
        Command command = msg.getCommand();
        if (command == Command.RESPONSE) {
            long id = msg.getId();
            Channel channel = ChannelUtil.REQUEST_MAPPING.get(id);
            if (Objects.nonNull(channel)) {
                channel.writeAndFlush(msg.getBytes());
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        if (cause instanceof TooLongFrameException) {
            log.error("too.long.frame.except.channel.ip: {}", ctx.channel().remoteAddress().toString());
            return;
        }
        log.warn("happen.except.channel.ip: {}", ctx.channel().remoteAddress().toString());
        log.error("this.error.msg: {}", cause.getMessage());
    }
}
